package com.zhugang.queue;


/**
 * @program algorithms
 * @description: 循环队列
 * @author: chanzhugang
 * @create: 2022/02/22 23:51
 */
public class CircleQueue {

    private final String[] array;
    private final int n;
    private int head;
    private int tail;

    public CircleQueue(int capacity) {
        this.array = new String[capacity];
        this.n = capacity;
        this.head = 0;
        this.tail = 0;
    }

    /**
     * 入队
     *
     * @param data
     * @return
     */
    public boolean enqueue(String data) {
        if ((tail + 1) % n == head) {
            // 队满
            return false;
        }
        array[tail] = data;
        tail = (tail + 1) % n;
        return true;
    }

    /**
     * 出队
     *
     * @return
     */
    public String dequeue() {
        if (head == tail) {
            // 队空
            return null;
        }
        String data = array[head];
        head = (head + 1) % n;
        return data;
    }

    /**
     * 打印
     */
    public void print() {
        for (int i = head; i % n != tail; i = (i + 1) % n) {
            System.out.println(array[i]);
        }
    }

    public static void main(String[] args) {
        CircleQueue queue = new CircleQueue(5);
        queue.enqueue("1");
        queue.enqueue("2");
        queue.enqueue("3");
        queue.enqueue("4");

        queue.print();

    }
}